var MutationViewerApp = MutationViewerApp || {};
MutationViewerApp.view = MutationViewerApp.view || {};

MutationViewerApp.view.ControlView = Backbone.View.extend({
    initialize: function(options) {
        this.dispatcher = options.dispatcher;
        this.initData();

        this.render();
    },

    initData: function() {
        var that = this;

        this.cancer_subtypes = [
            'BRCA',
            'COADREAD',
            'GBM',
            'KIRC',
            'LAML',
            'LUAD',
            'LUSC',
            'OV',
            'PRAD',
            'STAD',
            'UCEC'
        ];

        this.cancer_subtype_set = {};
        _.each(this.cancer_subtypes, function(subtype) {
            that.cancer_subtype_set[subtype] = 1;
        });
    },

    render: function() {
        var that = this;

        // Setup sortable list and text input with typeahead for
        // cancer subtypes.
        $('#subtype_list', this.$el).listcontrol({
            removableItems: true,
            storageId: "tumor_subtypes"
        });
        $('#subtype_list', this.$el).sortable({
            revert: true
        });
        $('#subtype_add_input', this.$el).typeahead({
            source: this.cancer_subtypes
        });
        $('.subtype_add_button', this.$el).click(function() {
            var subtype = $('#subtype_add_input', that.$el).val();
            if (_.has(that.cancer_subtype_set, subtype)) {
                $('#subtype_list', that.$el).add_item(subtype);
            }
        });

        // Setup text input with typeahead for choosing the gene to be displayed.
        $.ajax({
            url: "data/genes.tsv",
            method: "GET",
            success: function(txt) {
                $('#gene_select_input', that.$el).typeahead({
                    source: txt.split("\n")
                });
            }
        });
        $('.gene_select_button', this.$el).click(function() {
            var gene_label = $('#gene_select_input', that.$el).val();
            var cancer_subtypes = $('#subtype_list', that.$el).ordered_list();

            if (gene_label.length > 0 && cancer_subtypes.length > 0) {
                that.dispatcher.trigger('data:request:mutations', cancer_subtypes, gene_label);
            }
        });

        return this;
    }
});
